package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.PageParams;
import com.xuecheng.base.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.exception.XueChengPlusException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 杨振华
 * @since 2023/8/30
 */
@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;


    /**
     * 课程分页查询
     * @param pageParams
     * @param queryCourseParamsDto
     * @param companyId
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件，根据课程名称查询
        queryWrapper.like(StringUtils.isNotEmpty
                (queryCourseParamsDto.getCourseName()),
                CourseBase::getName,
                queryCourseParamsDto.getCourseName());
        //构建查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty
                (queryCourseParamsDto.getAuditStatus()),
                CourseBase::getAuditStatus,
                queryCourseParamsDto.getAuditStatus());
        //构建查询条件，根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),
                CourseBase::getStatus,
                queryCourseParamsDto.getPublishStatus()
        );
        // 构建查询条件，根据培训机构id查询
        queryWrapper.eq(CourseBase::getCompanyId, companyId);


        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<CourseBase> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;
    }

    /**
     * 添加课程
     *
     * @param companyId
     * @param addCourseDto
     * @return {@link CourseBaseInfoDto}
     */
    @Override
    @Transactional
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        // 参数合法性校验，使用@Validation

        // 向课程基本表写入数据
        CourseBase courseBase = new CourseBase();
        // 将addCourseDto放入到courseBase，对象拷贝
        BeanUtils.copyProperties(addCourseDto,courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setAuditStatus("202002");
        courseBase.setStatus("203001");
        int count = courseBaseMapper.insert(courseBase);
        if (count <= 0){
            throw new RuntimeException("添加课程失败！");
        }

        // 向课程营销表写入数据
        CourseMarket courseMarket = new CourseMarket();
        // 对象拷贝
        BeanUtils.copyProperties(addCourseDto, courseMarket);
        // 主键关联，课程id
        Long courseBaseId = courseBase.getId();
        courseMarket.setId(courseBaseId);
        // 保存营销信息
        saveCourseMarket(courseMarket);
        // 查询分类信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfoById(courseBaseId);

        return courseBaseInfo;
    }

    /**
     * 保存营销信息，存在则更新
     *
     * @param courseMarket
     * @return
     */
    public int saveCourseMarket(CourseMarket courseMarket){
        // 参数校验
        YingXiaoValidated(courseMarket);
        // 查询营销信息，存在更新，不存在添加
        Long id = courseMarket.getId();
        CourseMarket courseMarketInfo = courseMarketMapper.selectById(id);
        if (courseMarketInfo == null) {
            int count1 = courseMarketMapper.insert(courseMarket);
            return count1;
        }else {
            BeanUtils.copyProperties(courseMarket,courseMarketInfo);
            courseMarketInfo.setId(id);
            int count2 = courseMarketMapper.updateById(courseMarketInfo);
            return count2;
        }
    }
    /**
     * 根据课程id查询课程基本信息，包括基本信息和营销信息
     */
    @Transactional
    public CourseBaseInfoDto getCourseBaseInfoById(Long courseId){

        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;

    }

    /**
     * 更新课程基础
     *
     * @param companyId 公司标识
     * @param dto       dto
     * @return {@link CourseBaseInfoDto}
     */
    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) {
        Long courseId = dto.getId();
        // 查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase == null) {
            XueChengPlusException.cast("课程不存在！");
        }
        // 数据合法性校验
        // 根据具体业务逻辑进行校验，本机构修改本身的内容
        if (!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("不能修改其他机构的课程信息！");
        }
        // 封装数据
        BeanUtils.copyProperties(dto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        int count = courseBaseMapper.updateById(courseBase);
        if (count <= 0) {
            XueChengPlusException.cast("修改课程失败！");
        }
        /**
         * 更新营销信息
         */
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (courseMarket == null) {
            XueChengPlusException.cast("不存在营销信息！");
            courseMarket = new CourseMarket();
        }
        courseMarket.setId(courseId);
        YingXiaoValidated(courseMarket);
        BeanUtils.copyProperties(dto,courseMarket);
        int i = saveCourseMarket(courseMarket);
        if (i <= 0) {
            XueChengPlusException.cast("保存营销信息失败！");
        }
        CourseBaseInfoDto course = getCourseBaseInfoById(courseId);
        return course;
    }

    /**
     * 删除课程
     * @param courseId
     */
    @Override
    // TODO 但是这里课程计划还有视频的删除，所以这个到后期媒资管理部分进行完善
    public void deleteCourse(Long companyId, Long courseId) {
        CourseBase course = courseBaseMapper.selectById(courseId);
        if (course == null){
            XueChengPlusException.cast("该课程不存在！");
        }
        // 判断是否为本机构的课程
        if (!companyId.equals(course.getCompanyId())) {
            XueChengPlusException.cast("非本机构的课程无法删除！");
        }
        // 判断状态
        if (course.getAuditStatus().equals("202002")){
            // 只有在审核状态为未提交时才可以删除
            // 删除课程计划
            LambdaQueryWrapper<Teachplan> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1
                    .eq(Teachplan::getCourseId, courseId);
            teachplanMapper.delete(wrapper1);
            // 删除教师信息
            LambdaQueryWrapper<CourseTeacher> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2
                    .eq(CourseTeacher::getCourseId, courseId);
            courseTeacherMapper.delete(wrapper2);
            // 删除营销信息
            courseMarketMapper.deleteById(courseId);
            courseBaseMapper.deleteById(courseId);
        }
    }

    /**
     * 营销校验
     *
     * @param courseMarket 当然市场
     */
    private static void YingXiaoValidated(CourseMarket courseMarket) {
        // 参数校验
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
            throw new RuntimeException("收费规则没有选择");
        }
        //收费规则为收费
        if(charge.equals("201001")){
            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue()<=0){
                XueChengPlusException.cast("课程为收费价格不能为空且必须大于0");
            }
        }
    }
}
